import { useState, useEffect, useRef } from "react";
import "./index.css"
import { queryCourse, searchCourse } from "../../../api/index"
import Card from "../Card"
import { Spin } from "antd";

const tags = ["最新", "最热", "折扣"]

// 分页触底加载
let allCourses = null
let limit = 20
let offset = 0

function Course({ searchKey }) {
    // console.log(searchKey)
    const [focusIndex, setFocusIndex] = useState(0)
    function handleClick(index) {
        setFocusIndex(index)
        refreshData(index + 1)
    }
    const [isLoading, setIsloading] = useState(true)

    const [cards, setCards] = useState([])
    useEffect(() => {
        if (searchKey) {
            searchData(searchKey);
            return;
        }
        // setFocusIndex(0);
        refreshData();
    }, [searchKey]);
    async function searchData(title) {
        // console.log(title)
        if (!title) {
            return
        }
        setIsloading(true)
        const res = await searchCourse({ title })
        setIsloading(false)
        
        allCourses = res.data;
        offset = 0;
        setCards(res.data.slice(0, limit))
        offset = offset + limit;
    }
    async function refreshData(type = 1) {
        setIsloading(true)
        const res = await queryCourse({ type })
        setIsloading(false)

        allCourses = res.data;
        offset = 0;
        setCards(res.data.slice(0, limit));
        offset = offset + limit;
    }

    const loaderRef = useRef(null)
    useEffect(() => {
        const observer = new IntersectionObserver(
          (entries) => {
            if (entries[0].isIntersecting) {
              moreData();
            }
          },
          { rootMargin: "0px 0px 100% 0px" }
        );
        if (loaderRef.current) {
          observer.observe(loaderRef.current);
        }
        return () => {
          if (loaderRef.current) {
            observer.unobserve(loaderRef.current);
          }
        };
      }, [loaderRef.current]);
      const moreData = () => {
        if (!allCourses || offset >= allCourses.length) {
          return;
        }
        setCards(allCourses.slice(0, offset + limit));
        offset = offset + limit;
      };
    return (
        <div className="Course">
            <div className="header-tags">
                {!searchKey && tags.map((item, index) => {
                    return (
                        <div className={index === focusIndex ? "item item-focus" : "item"}
                            onClick={() => handleClick(index)}
                            key={index}
                        >
                            {item}
                        </div>
                    )
                })}
            </div>
            <Spin spinning={isLoading}>
                <div className="Courses">
                    {/* <Card course = {{
                     "coverImg": "https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/efeb8e1a01904b0690128627433d2552~tplv-k3u1fbpfcp-watermark.image?",
  "title": "Nest 通关秘籍",
  "summary": "掌握 Nest 和各种后端中间件，通过大量实战成为真正的全栈工程师！",
  "buyCount": 2216,
  "price": "89.9",
  "isDiscount": true,
  "discountPrice": "53.94",
  "returnRedPacket": "17.98",
  "shareUrl": "https://juejin.cn/book/7226988578700525605?suid=3350967171169901&source=pc"
                }}
                ></Card> */}
                    {
                        cards.map((card) => <Card className="Card" key={card.title} course={card}></Card>)
                    }
                </div>
            </Spin>
            <div ref={loaderRef} />

        </div>
    );
}
export default Course;